package com.niodata.dp.monitor.core.task.dao.handler;

import com.niodata.dp.monitor.core.task.entity.TaskOptions;
import com.niodata.dp.monitor.core.task.util.JsonUtil;
import com.niodata.dp.mybatis.DpMybatisTypeHandler;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;


public class TaskOptionTypeHandler extends BaseTypeHandler<TaskOptions> implements
      DpMybatisTypeHandler {

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.LONGNVARCHAR;
  }

  @Override
  public Class getTypeHandlerClass() {
    return TaskOptionTypeHandler.class;
  }

  @Override
  public Class getJavaClass() {
    return TaskOptions.class;
  }

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, TaskOptions parameter,
        JdbcType jdbcType) throws SQLException {
    if (parameter == null) {
      ps.setString(i, null);
    }
    try {
      String json = JsonUtil.toJson(parameter);
      ps.setString(i, json);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public TaskOptions getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String json = rs.getString(columnName);
    if (json == null) {
      return null;
    }
    try {
      return (TaskOptions) JsonUtil.fromJson(getJavaClass(), json);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public TaskOptions getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String json = rs.getString(columnIndex);
    if (json == null) {
      return null;
    }
    try {
      return (TaskOptions) JsonUtil.fromJson(getJavaClass(), json);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public TaskOptions getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return null;
  }
}
